<?php

class lfDAO
{

	protected function __construct()
	{
		$dbinfo = lfApplication::GetInstance()->DATABASE_INFO();
		$this->mysql = new lfMySQL();
		$this->mysql->Connect($dbinfo["host"], $dbinfo["user"], $dbinfo["passwd"], 'UTF8');
		$this->mysql->OpenDB($dbinfo["dbname"]);
	}

	/**
	 * 初始化一个主表名
	 *
	 * @param string $primaryTable
	 * @return DAO
	 */
	function Init($primaryTable)
	{
		$this->primary_table = $primaryTable;
		$this->table_list[] = $primaryTable;
		$this->source_part = $primaryTable;
		return $this;
	}

	function __destruct()
	{
		$this->mysql->Close();
	}

	/**
	 * 处理表联接
	 *
	 * @param string $table_name
	 * @param string $left_field
	 * @param string $right_field
	 * @return DAO
	 */
	function Join($table_name, $left_field = NULL, $right_field = 'id')
	{
		$tmp_left_field = empty($left_field) ? $table_name . '_id' : $left_field;
		
		$this->source_part .= " LEFT JOIN $table_name ON $this->primary_table.$tmp_left_field = $table_name.$right_field";
		echo $this->source_part;
		$this->table_list[] = $table_name;
		return $this;
	}

	function __call($func_name, $arguments)
	{
		
		$query_type = $this->GetQueryTypeFromName($func_name);
		$by_pos = strpos($func_name, "By");
		
		//		is_numeric($arguments[0]) ? print 1: print 2;
		

		$customer_condition = $arguments[0];
		
		if ($by_pos)
		{
			$byValue = is_numeric($arguments[0]) ? $arguments[0] : "'" . $arguments[0] . "'";
			echo $byValue;
			$customer_condition = strtolower(substr($func_name, $by_pos + 2)) . "=$byValue";
		}
		
		//		$customer_condition = $by_pos ? strtolower(substr($func_name, $by_pos + 2)) . "=$arguments[0]" : $arguments[0];
		

		switch ($query_type)
		{
		case 'Get' :
			$pageIndex = isset($arguments[1]) ? $arguments[1] : 1;
			return $this->DoGetFunction(str_replace('__', '.', $customer_condition), $pageIndex);
		break;
		case 'Set' :
			return $this->DoSetFunction(str_replace('__', '.', $customer_condition), $arguments[1]);
		break;
		case 'Add' :
			return $this->DoAddFunction($arguments[0]);
		break;
		case 'Del' :
			return $this->DoDelFunction(str_replace('__', '.', $customer_condition));
		break;
		default :
			echo "error:<br />";
		break;
		}
		echo "sdf";
	
	}

	/**
	 * 打印本次执行的SQL语句
	 *
	 */
	function print_sql()
	{
		echo $this->sql;
	}

	/**
	 * 设置要查询的字段列表
	 *
	 * @param string $str_field_list
	 * @return DAO
	 */
	function FIELDS($str_field_list = '*')
	{
		$this->field_part = $str_field_list;
		if ($str_field_list == '*')
			return $this->field_part;
		return $this;
	}

	/**
	 * 设置分页查询时第页要显示的行数
	 *
	 * @param int $rowsCount
	 * @return DAO
	 */
	function PAGE_SIZE($pageSize = 0)
	{
		$this->pageSize = $pageSize;
		if (! $pageSize)
			return $this->pageSize;
		return $this;
	}

	private function DoGetFunction($condition, $pageIndex)
	{
		$sql_condition = $this->SqlCondition($condition);
		$sql = "SELECT $this->field_part FROM $this->source_part WHERE 1 AND ($sql_condition)";
		
		$arCnt['cnt'] = 0;
		$pageCount = 1;
		if ($this->pageSize)
		{
			$sql_cnt = "SELECT count(*) AS cnt FROM $this->source_part WHERE 1 AND ($sql_condition)";
			$cntRs = $this->mysql->Execute($sql_cnt);
			$arCnt = mysql_fetch_assoc($cntRs);
			$sql .= $this->pageSize ? " limit " . $this->pageSize * ($pageIndex - 1) . ",$this->pageSize" : "";
			
			$pageCount = ceil(floatval($arCnt['cnt']) / $this->pageSize);
		}
		
		$recordSet = new lfRecodeSet();
		$recordSet->SetData($this->mysql->Execute($sql), $arCnt['cnt'], $pageCount);
		
		return $recordSet;
	}

	private function DoAddFunction($values)
	{
		$sql = "INSERT INTO $this->primary_table SET $values";
		$this->sql = $sql;
		$this->mysql->Execute($sql);
		return true;
	}

	private function DoSetFunction($condition, $values)
	{
		$sql_condition = $this->SqlCondition($condition);
		$sql = "UPDATE $this->source_part SET $values WHERE 1 AND ($condition)";
		$this->sql = $sql;
		$this->mysql->Execute($sql);
		return true;
	}

	private function DoDelFunction($condition)
	{
		$sql_condition = $this->SqlCondition($condition);
		$sql = "DELETE FROM $this->source_part WHERE 1 AND ($sql_condition)";
		$this->mysql->Execute($sql);
		$this->sql = $sql;
	}

	/**
	 * 从函数名字中分析查询的类型
	 *
	 * @param unknown_type $func_name
	 * @return unknown
	 */
	private function GetQueryTypeFromName($func_name)
	{
		if (strpos("xx$func_name", "Get") == 2)
		{
			$this->qeury_type = "SELECT ";
			return "Get";
		}
		elseif (strpos("xx$func_name", "Add") == 2)
		{
			$this->qeury_type = "INSERT INTIO ";
			return "Add";
		}
		elseif (strpos("xx$func_name", "Del") == 2)
		{
			$this->qeury_type = "DELETE FROM ";
			return "Del";
		}
		elseif (strpos("xx$func_name", "Set") == 2)
		{
			$this->qeury_type = "UPDATE ";
			return "Set";
		}
		else
		{
			echo "查询类型不明确，请用  | Add | Del | Set | Get | 指定";
			return false;
		}
	
	}

	/**
	 * 得到给定表名的所有字段
	 *
	 * @param unknown_type $table
	 * @return unknown
	 */
	private function GetTableFields($table)
	{
		$sql = "show columns from $table";
		$rs = $this->mysql->Execute($sql);
		
		while( $field = mysql_fetch_assoc($rs) )
		{
			$field_array[] = $field['Field'];
		}
		return $field_array;
	}

	/**
	 * 把指定的字段的简名得到全名
	 *
	 * @param unknown_type $field_short
	 * @return unknown
	 */
	private function FieldFullname($field_short)
	{
		foreach ( $this->table_list as $table )
		{
			$field_list = $this->GetTableFields($table);
			
			foreach ( $field_list as $field )
			{
				if (strpos("xx$field", $field_short))
				{
					return $field;
				}
			}
		}
		
		return $field_short;
	}

	/**
	 * 从自定义的条件中分析出可以被执行的SQL的条件
	 *
	 * @param unknown_type $customer_condition
	 * @return unknown
	 */
	private function SqlCondition($customer_condition)
	{
		if (! function_exists("oprator_pos"))
		{

			function oprator_pos($str_contain_oprator)
			{
				if ($opt_pos = strpos($str_contain_oprator, ">="))
					return $opt_pos;
				if ($opt_pos = strpos($str_contain_oprator, "<="))
					return $opt_pos;
				if ($opt_pos = strpos($str_contain_oprator, "!="))
					return $opt_pos;
				if ($opt_pos = strpos($str_contain_oprator, "="))
					return $opt_pos;
				if ($opt_pos = strpos($str_contain_oprator, "<"))
					return $opt_pos;
				if ($opt_pos = strpos($str_contain_oprator, ">"))
					return $opt_pos;
				return 0;
			}
		}
		$ar_condition = split(" ", $customer_condition);
		
		$sql_condition = '';
		foreach ( $ar_condition as $sub_condition )
		{
			$field_short = substr($sub_condition, 0, oprator_pos($sub_condition));
			
			if ($field_short != "")
				$sub_condition = str_replace($field_short, $this->FieldFullname($field_short), $sub_condition);
			$sql_condition .= $sub_condition . " ";
		}
		
		return trim($sql_condition) == "" ? 1 : $sql_condition;
	}
	private $primary_table = '';
	
	/**
	 * Enter MySQL 类的一个引用
	 *
	 * @var MySQL
	 */
	private $mysql = NULL;
	private $source_part = '';
	private $field_part = '*';
	private $condition_part = '';
	private $qeury_type = '';
	private $table_list = array();
	private $sql;
	
	private $pageIndex = 0;
	private $pageSize = 0;

	/**
	 * 创建DAO对象
	 *
	 * @param string $tableName
	 * @return DAO
	 */
	static function GetInstance($tableName)
	{
		global $___dao___;
		
		if (is_null($___dao___))
		{
			$___dao___ = new lfDAO();
		}
		
		$___dao___->Init($tableName);
		
		return $___dao___;
	}
}

?>